package com.laobiao.file_netty_lib.util;

import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;

public class InetUtil {
	/**
	 * 获取当前系统可用TCP端口，返回-1代表无端口可用
	 * 
	 * @return
	 */
	public static int getTcpUsablePort(int minPort, int maxPort) {
		InetAddress inet = null;
		try {
			inet = InetAddress.getByName("127.0.0.1");
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
			return -1;
		}
		for (int i = minPort; i <= maxPort; i++) {
			try {
				ServerSocket socket = new ServerSocket(i);
				socket.close();
				return i;
			} catch (Exception e) {
			}
		}
		return -1;
	}
	
	 /**
     * 获取当前系统可用UDP端口，返回-1代表无端口可用
     * @return
     */
	public static int getUdpUsablePort(int minPort, int maxPort){
        InetAddress inet=null;
		try {
			inet=InetAddress.getByName("127.0.0.1");
		} catch (UnknownHostException e1) {
            e1.printStackTrace();
            return -1;
		}
		for(int i=minPort;i<=maxPort;i++){
			try {
                DatagramSocket ds=new DatagramSocket(i);
                ds.close();
				return i;
			} catch (Exception e) {
			}
        }
        return -1;
    }
	
}
